<template>
  <div class="city">
    <div class="title"><van-icon name="arrow-left" @click="$router.back()" /><span>城市列表</span></div>
    <div class="list">
      <van-index-bar :index-list="newWordList" :sticky="false">
         <van-index-anchor>当前城市</van-index-anchor>
         <van-cell :title="cityInfo.label" :index="cityInfo.label"/>
         <van-index-anchor>热门城市</van-index-anchor>
         <van-cell :title="hot.label" v-for="hot in hotCityList" :key="hot.pinyin" :index="hot" @click="citySelectName(hot)"  />
        <div  v-for="(word,index) in newWordList.slice(2)" :key="index">
          <van-index-anchor :index="word"/>
            <van-cell v-for="item in cityList" :key="item.pinyin" :title="item.label" v-show="item.short.split('')[0].toUpperCase()===word" @click="citySelectName(item)"/>
        </div>
      </van-index-bar>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
export default {
  name: 'City',
  data () {
    return {
      cityInfo: {
        label: '北京',
        value: localStorage.getItem('code') || 'AREA|88cff55c-aaa4-e2e0'
      },
      // 城市渲染的右侧字母
      newWordList: [],
      // 城市列表
      cityList: []
    }
  },
  created () {
    this.cityInfoList()
    this.hotCityInfoList()
  },
  methods: {
    // 城市列表获取
    async cityInfoList () {
      this.$Toast.loading({ duration: 0, forbidClick: true, message: '加载中...' })
      await this.$store.dispatch('confirmCityList')
      // this.$store.state.city.cityList只是简单的赋值
      this.$store.state.city.cityList.forEach(city => {
        this.newWordList.push(city.short.split('')[0].toUpperCase())
        this.newWordList = [...new Set(this.newWordList)]
      })
      this.newWordList.sort((a, b) => {
        if (a > b) return 1
        else return -1
      })
      this.newWordList.unshift('#', '热')
      this.cityList = this.$store.state.city.cityList || []
      this.$Toast.clear()
    },
    // 热门城市列表
    async hotCityInfoList () {
      await this.$store.dispatch('confirmHotCityList')
    },
    // 点击IndexBar Events
    citySelectName (city) {
      // console.log(city)
      this.cityInfo.label = city.label
      this.cityInfo.value = city.value
      localStorage.setItem('city', city.label)
      localStorage.setItem('code', city.value)
      this.$router.go(-1)
    }
  },
  computed: {
    ...mapState({
      // 热城市列表
      hotCityList: (state) => state.city.hotCityList || []
    })
  }
}
</script>

<style lang='less' scoped>
.city{
  padding-top: 40px;
  .title{
    position: fixed;
    z-index: 999;
    top: 0;
    left: 0;
    width: 100%;
    height: 40px;
    background-color:#43b978;
    text-align: center;
    line-height: 40px;
    color: #fff;
    font-size: 18px;
    .van-icon-arrow-left{
      left: 15px;
      top: 10px;
      position: absolute;
      color: #fff;
      font-size: 16px;

    }

  }
  .van-index-anchor{
    font-size: 12px;
  }

}

</style>
